package com.janko.springbootbase.juc.reentrantlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author nyk
 * @Date 2021/4/16 18:13
 * @Version 1.0
 * @Desc
 */
public class MyReentrantLock {
    private int state;//记录当前打印的状态
    private int times;//记录打印的次数

    private Lock lock= new ReentrantLock();
    public MyReentrantLock(int times) {
        this.times = times;
    }

    void PrintLatter(String name,int tarNums){
        for (int i = 0; i < times; ) {
            lock.lock();
            if (state % 3 == tarNums) {
                state++;
                times++;
                System.out.println(name);
            }
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        MyReentrantLock look = new MyReentrantLock(1);
        new Thread(() -> {
            look.PrintLatter("B", 1);
        },"线程B").start();
        new Thread(() -> {
            look.PrintLatter("A", 0);
        },"线程A").start();
        new Thread(() -> {
            look.PrintLatter("C", 2);
        },"线程C").start();
    }
}

